package com.itheima.wemedia.service.impl;

import com.alibaba.fastjson.JSON;
import com.itheima.admin.feign.AdChannelFeign;
import com.itheima.admin.pojo.AdChannel;
import com.itheima.common.constants.SystemConstants;
import com.itheima.common.exception.LeadNewsException;
import com.itheima.common.vo.ResultVo;
import com.itheima.wemedia.service.ApiService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.List;

@Service
@Slf4j
public class ApiServiveImpl implements ApiService {

    @Autowired
    private AdChannelFeign adChannelFeign;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;


    /**
     * 调用后台微服务，获取频道列表。
     * 优先使用redis缓存
     *
     * @return
     */
    @Override
    public List<AdChannel> channelList() {
        //redis获取
        String channelJsonList = stringRedisTemplate.opsForValue().get(SystemConstants.REDISKEY_CHANNELLIST);
        List<AdChannel> channelList= null;
        if (!StringUtils.isEmpty(channelJsonList)){
            channelList = JSON.parseArray(channelJsonList,AdChannel.class);
        }
        //redis无值
        if (CollectionUtils.isEmpty(channelList)){
            ResultVo<List<AdChannel>> listResultVo = adChannelFeign.listAll();
            if (!listResultVo.isSuccess()){
                throw new LeadNewsException("调用后台查询频道失败");
            }
            channelList = listResultVo.getData();

            stringRedisTemplate.opsForValue().set(SystemConstants.REDISKEY_CHANNELLIST,JSON.toJSONString(channelList));
        }
        return channelList;
    }
}
